const http = require("http");
const fs = require("fs");
const path = require("path");

var imgList = [];

http.createServer((req,res) => {
    var urlObj = new URL(req.url, "http://localhost:8081/getlist");
    var pathName = urlObj.pathname;

    if(pathName == "/getlist"){
        var fileContent = fs.readFileSync("./list.html");
        res.writeHead(200, {"Context-Type": "text/html;charset=utf8"});
        res.write(fileContent);
        res.end();
    }
    else if(pathName == "/list"){
        var fileDirPath = path.join(__dirname, "/upload");
        fs.readdir(fileDirPath, (err, files) => {
            if(err){
                console.log(err);
            }
            else{
                files.forEach((item, index) => {
                    var buf = Buffer.from(item, "binary");
                    imgList.push(buf);
                    res.writeHead(200, {"Context-Type": "text/html;charset=utf8"});
                    res.end(imgList)
                })
            }
        })
    }
}).listen(8081);

